import React, {useEffect, useState} from 'react';
import {Button, Modal, Table, Tree} from "antd";
import axios from "axios";
import {DeleteOutlined, UnorderedListOutlined, ExclamationCircleOutlined} from "@ant-design/icons";

const {confirm} = Modal;


export default function RoleList() {
    const [dataSource, setDataSource] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [rightList, setRightList] = useState([]);
    const [currentRights, setCurrentRights] = useState([]);
    const [currentId, setCurrentId] = useState([]);

    useEffect(() => {
        axios.get('/roles').then(res => {
            console.log(res.data)
            setDataSource(res.data)
        })
        axios.get('/rights?_embed=children').then(res => {
            // console.log(res.data)
            setRightList(res.data)
        })

    }, [])

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render: (id) => {
                return <b>{id}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
        },
        {
            title: '操作',
            render: (item) => {
                return <div className='noselect'>
                    <Button type="primary" shape="circle" icon={<UnorderedListOutlined/>}
                            onClick={() => showModal(item)}/>
                    &nbsp;&nbsp;
                    <Button danger shape="circle" icon={<DeleteOutlined/>} onClick={() => confirmDel(item)}/>
                </div>
            }
        },
    ]


    // 弹出对话框
    const showModal = (item) => {
        setIsModalVisible(true);

        // 获取被点击项的 right (需要被选中的路径)
        setCurrentRights(item.rights)
        // 获取被点击项的 id
        setCurrentId(item.id)
    };
    // 关闭对话框
    const handleOk = () => {
        setIsModalVisible(false);

        // 页面数据同步
        setDataSource(dataSource.map(item => {
            if (item.id === currentId){
                return {
                    ...item,
                    rights: currentRights
                }
            }
            return item
        }))

        // 将调整之后的权限选择 checkedKeys 同步回后端
        axios.patch(`/roles/${currentId}`, {
            rights: currentRights
        })
    };
    // 关闭对话框
    const handleCancel = () => {
        setIsModalVisible(false);
    };

    // 树状控件中，切换选项框是否被选中的函数
    const onCheck = (checkedKeys) => {
        console.log(checkedKeys)
        setCurrentRights(checkedKeys.checked)
    }


    // 删除确认提示框
    const confirmDel = (item) => {
        confirm({
            title: '你确定要删除?',
            icon: <ExclamationCircleOutlined/>,
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                deleteMethod(item)
            },
            onCancel() {
                console.log('取消');
            },
        });
    }

    // 确认删除后执行的函数
    const deleteMethod = (item) => {
        console.log(item);

        setDataSource(dataSource.filter(data => data.id !== item.id))
        // 后端同步
        axios.delete(`/roles/${item.id}`).then()
    }

    return (
        <div>
            <Table dataSource={dataSource} columns={columns}
                   rowKey={item => item.id}/> {/* 因为返回的数据中没有 key 属性，所以需要自己设置一个 rowKey */}

            {/* 弹出框 */}
            <Modal title="权限分配" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel} okText='确认'
                   okType='primary' cancelText='取消'>
                <Tree
                    checkable
                    checkedKeys={currentRights}
                    // checkable 状态下节点选择完全受控（父子节点选中状态不再关联）
                    checkStrictly={true}
                    onCheck={onCheck}
                    treeData={rightList}
                />
            </Modal>
        </div>
    )
}